const query = require("../sql/db")

const methods = {
  // 查询整张表
  selectTable: (tableName) => {
    return new Promise((resolve, reject) => {
      const sql = `SELECT * FROM ${tableName}`
      query(sql, (err, res) => {
        if (err) {
          return reject(err)
        }
        resolve(res)
      })
    })
  },

  /**
   * 简单where查询
   * @param {string} tableName 表名
   * @param {Object} condition 查询条件
   * @param {string} condition.field 字段名
   * @param {string} condition.operator 运算符，不设置时默认为'='
   * @param {string} condition.value 字段值
   * @returns {Array}
   */
  selectSimpleWhere: (tableName, condition = null) => {
    return new Promise((resolve, reject) => {
      const { field, operator, value } = condition
      const sql = `SELECT * FROM ${tableName} WHERE ${field} ${
        operator || "="
      } '${value}'`
      query(sql, (err, res) => {
        if (err) {
          return reject(err)
        }
        resolve(res)
      })
    })
  },

  /**
   * 向表中添加单条记录
   * @param {string} tableName 表名
   * @param {Object} data 数据对象
   */
  insertRow: (tableName, data = {}) => {
    return new Promise((resolve, reject) => {
      const sql = `INSERT INTO ${tableName} set ?`
      query(sql, data, (err, res) => {
        if (err) {
          return reject(err)
        }
        resolve(res)
      })
    })
  },
}

module.exports = methods
